package nl.xvr.server.web;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.Properties;

public class WebServer extends Thread {
    private int port;
    private String webroot;
    private String defaultpage;
    private boolean dir_browsing;

    private ServerSocket sockListen = null;

    public WebServer(Properties properties) {
        this.port = Integer.parseInt(properties.getProperty("web_port"));
        this.webroot = properties.getProperty("webroot");
        this.defaultpage = properties.getProperty("defaultpage");
        if (properties.getProperty("dir_browsing").isEmpty()) {
            this.dir_browsing = false;
        } else {
            this.dir_browsing = true;
        }
    }

    @Override
    public void run() {
        try {
            System.out.println("Start web server...");
            sockListen = new ServerSocket(port);

            while (true) {
                try {
                    new RequestHandler(webroot, defaultpage, dir_browsing, sockListen.accept(), WebServerLogger.createLogger()).start();
                }
                catch (IOException e) {
                    //                    System.err.println("Could not accept socket listener for web server: " 
                    //                            + e);
                    return;
                }
            }
        } catch (IOException e) {
            System.err.println("Could not start web server: " + e);
            System.exit(-1);
        }
    } 

    public void closeServer() {
        try {
            sockListen.close();
        } catch (IOException e) {
            System.err.println("Could not stop server: " + e);
        }
    }
}
